package net.phoenix.repository.query;

import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Workspace;
import javax.jcr.query.InvalidQueryException;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.jcr.query.qom.QueryObjectModelFactory;

import net.phoenix.repository.query.jql.JQLQuery;
import net.phoenix.repository.query.sql.SQLQuery;
import net.phoenix.repository.query.xpath.XPathQuery;



/**
 * 
 * @author lixf
 * 
 */
public class BasicQueryManager implements QueryManager{
	private QueryObjectModelFactory factory;
	private Workspace workspace;
	private String[] supportLanguages= {"XPATH","SQL"};

	public BasicQueryManager(Workspace workspace) {
		this.factory = null;
		this.workspace = workspace;		
	}


	@Override
	public String[] getSupportedQueryLanguages() {
		return this.supportLanguages;
	}

	@Override
	public Query createQuery(String statement, String language) throws InvalidQueryException, RepositoryException {
		if(statement==null)
			throw new InvalidQueryException("statement should not be null. ");
		GeneralQuery query = null;
		if(language.equalsIgnoreCase("XPATH"))
			query = new XPathQuery();
		else if(language.equalsIgnoreCase("SQL"))
			query = new SQLQuery();
		else if(language.equalsIgnoreCase("JCR-SQL2"))
			query = new JQLQuery();
		if(query == null)
			throw new InvalidQueryException("Unknown language : " + language);
		query.init(workspace, statement);
		return query;
	}

	@Override
	public QueryObjectModelFactory getQOMFactory() {
		return factory;
	}

	@Override
	public Query getQuery(Node node) throws InvalidQueryException, RepositoryException {
		String language = node.getProperty("language").getString();
		String statement = node.getProperty("statement").getString();
		return createQuery(statement, language);
	}

}
